const { db, genid } = require('../database/index');

const articleHandler = {
  // 添加
  async articleAdd(req, res) {
    const { title, categoryId, content } = req.body;
    let id = genid.NextId();
    let createTime = new Date().getTime();
    let content1 = content.replace(/"/g, "'")

    const sqlInsertStr = `INSERT INTO 
                articles 
                VALUES (${id},${categoryId},'${title}',"${content1}",${createTime})`;

    const out = await db.async(sqlInsertStr);
    if (out.err) return res.jgcl(out.err, 500);

    res.jgcl('文章添加成功！', 200);
  },
  // 修改
  async articleUpdate(req, res) {
    const { id, title, categoryId, content } = req.body;
    const sqlUpdateStr = `UPDATE 
                articles 
                SET 
                  title = '${title}',
                  categoryId=${categoryId},
                  content='${content}' 
                WHERE id = ${id}`;

    const out = await db.async(sqlUpdateStr);
    if (out.err) return res.jgcl(out.err, 500);

    res.jgcl('文章更新成功！', 200);
  },
  // 删除
  async articleDelete(req, res) {
    let id = req.query.id;
    const sqlDeleteStr = `DELETE FROM articles WHERE id = ${id}`;

    const out = await db.async(sqlDeleteStr);
    if (out.err) return res.jgcl(out.err, 500);

    res.jgcl('文章删除成功！', 200);
  },
  // 查找
  async articliSerch(req, res) {
    let { keyword, categoryId, page, pageSize } = req.query

    page = page == null ? 1 : page;
    pageSize = pageSize == null ? 6 : pageSize;
    categoryId = categoryId == null ? 0 : categoryId;
    keyword = keyword == null ? '' : keyword;

    const whereSqls = [];
    if (categoryId != 0) {
      whereSqls.push(` categoryId = ${categoryId}`);
    }
    if (keyword != '') {
      whereSqls.push(` (title LIKE '%${keyword}%' OR content LIKE '%${keyword}%')`)
    }
    let whereSqlStr = "";
    if (whereSqls.length > 0) {
      whereSqlStr = ` WHERE ${whereSqls.join(' AND')}`;
    }

    const sqlSelectStr = `SELECT 
                * 
                FROM articles
                ${whereSqlStr}
                ORDER BY createTime
                DESC LIMIT ${(page - 1) * pageSize} , ${pageSize}`;

    const out = await db.async(sqlSelectStr);

    if (out.err) return res.jgcl(out.err, 500);

    const sqlSelectStr2 = `SELECT 
                * 
                FROM articles`
    const out2 = await db.async(sqlSelectStr2);

    res.send({
      status: {
        code: 200,
        msg: '文章查询成功！'
      },
      data: {
        reqStr: {
          keyword, categoryId, page, pageSize
        },
        rows: out,
        count: out2.length,
      }
    })
  },
  // 根据 id 查找
  async detailSerch(req, res) {
    const { id } = req.query
    const sqlSelectStr = `SELECT * FROM articles WHERE id = ${id}`
    const out = await db.async(sqlSelectStr);
    if (out.err) return res.jgcl(out.err, 500);
    res.jgcl('查询成功', 200, out)

  }
}

module.exports = articleHandler